package com.bestv.search.management.datasyn;

import com.bestv.search.common.cache.SystemCache;
import com.bestv.search.management.command.FilterCommand;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;
import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.Date;

/**
 * @author Michael Wang
 */

// $Id$
public class FilterJob extends QuartzJobBean {

    static boolean isRunning = false;
    static String filterFile = "filterWords.properties";
    Logger logger = Logger.getLogger(FilterJob.class);
    private FilterCommand filterCommand;
    private SystemCache systemCache;

    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        if (!isRunning) {
            isRunning = true;
            run();
        } else {
            logger.error("Last filter process is still running");
        }
    }

    void run() {
        logger.info("Start filter job @" + new Date());
        PropertiesConfiguration config;
        try {
            config = new PropertiesConfiguration(filterFile);
            config.setReloadingStrategy(new FileChangedReloadingStrategy());
            String filterStr = config.getString("filter");
            String[] filterArr = filterStr.split("_");
            filterCommand.filter(filterArr, systemCache.getLocalDataSourceKey());
            String sensitiveStr = config.getString("sensitive");
            String[] sensitiveArr = sensitiveStr.split("_");
            filterCommand.sensitive(sensitiveArr, systemCache.getLocalDataSourceKey());
        } catch (Exception e) {
            logger.error(e.getMessage());
            isRunning = false;
        }
        logger.info("End filter job @" + new Date());
        isRunning = false;
    }

    public FilterCommand getFilterCommand() {
        return filterCommand;
    }

    public void setFilterCommand(FilterCommand filterCommand) {
        this.filterCommand = filterCommand;
    }

    public SystemCache getSystemCache() {
        return systemCache;
    }

    public void setSystemCache(SystemCache systemCache) {
        this.systemCache = systemCache;
    }
}
